<template>
  <div class="exercises-box inner-content">
    <div class="inner inner-content-box">
      <div class="searchBox">
        <el-form
          :inline="true"
          :model="searchForm"
          size="small"
          style="width: 100%"
          @keyup.enter.native="getList(1)"
        >
          <el-form-item>
            <el-input v-model="searchForm.examName" placeholder="题目名称" clearable style="width: 160px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchForm.examTypeName" placeholder="考题类型" clearable style="width: 160px"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="flex-start" style="align-items: flex-start">
              <el-button type="primary" @click="getList(1)" icon="el-icon-search">查询</el-button>
              <el-button @click="clearHandle()" icon="el-icon-delete-solid">清空</el-button>
            </div>
          </el-form-item>
          <br />
          <el-form-item>
            <div class="flex-start" style="align-items: flex-start">
              <el-button v-if="isAuth('exercisesAdd')" size="small" type="warning" icon="el-icon-plus" @click="showExercises">创建考题</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="detailsBox" ref="tableBox">
        <ag-grid-vue
          class="ag-theme-alpine ag-theme-quartz"
          :gridOptions="gridOptions"
          :localeText="localeText"
          @grid-ready="onGridReady"
          @selection-changed="getSelectedRows"
          @sort-changed="onSortChangedAggrid"
          @filter-changed="onFilterChangedAggrid"
          :rowHeight="38"
          :headerHeight="42"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :rowData="rowData"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :enableRangeSelection="true"
        >
        </ag-grid-vue>
      </div>
      <div class="pageBox">
        <div>
          选择 <strong style="color: #00b99e;">{{ dataSelect.length }}</strong> 数据
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>
    <div>
      <tiganDialog ref="tiganDialog" :examinationIdDialog='examinationIdDialog' :exercisesDialogBak='exercisesDialogBak' @closeHandle='closeHandle' :passwordCheck="passwordCheck"></tiganDialog>
      <el-dialog
        title="校验密码"
        :visible.sync="passwordVisible"
        width="500px"
        :before-close="handleClosePwd">
        <div>
          <el-form :model="passwordForm" :rules="passwordFormRules" ref="passwordForm" label-width="160px" style="padding-right: 30px;padding-top: 10px;" label-position="right">
            <el-form-item label="请输入密码：" prop="password">
              <el-input type="password" style="width: 240px" v-model="passwordForm.password" autocomplete="off" placeholder="请输入密码"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClosePwd">取 消</el-button>
          <el-button type="primary" @click="submitPassword('passwordForm')">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import jsonData from '@/assets/json/data.json'
import scoreCard from '@/views/modules/exercises/scoreCard.vue'
import selfinspectionCard from '@/views/modules/exercises/selfinspectionCard.vue'
import cueCard from '@/views/modules/exercises/cueCard.vue'
import exampoints from '@/views/modules/exercises/exampoints.vue'
import tiganDialog from '@/views/modules/exercises/tiganDialog.vue'
import listBtn from '@/views/modules/exercises/tiGanBtn.vue'
import listJson from '@/views/modules/exercises/tigan.json'
import { authCheck, initializePwd } from '@/api/index'
import Vue from 'vue'
export default {
  components: {
    scoreCard,
    selfinspectionCard,
    cueCard,
    exampoints,
    tiganDialog,
    listBtn
  },
  beforeMount () {
    this.gridOptions = {
      // 通过这个属性建立了上下文引用
      context: { componentParent: this }
      // 说人话就是可以在自己声明的组件里调用到父组件的方法和属性了
    }
  },
  watch: {
    $route: {
      handler (newValue, oldValue) {
        if (oldValue.name === 'exercises-tigan') {
          this.exercisesDialogBak = false
        }
      },
      deep: true
    }
  },
  data () {
    return {
      gridOptions: null,
      localeText: this.$AG_GRID_LOCALE_ZZZ,
      col: [],
      defaultColDef: {
        editable: false,
        sortable: true,
        resizable: true,
        filter: true,
        cellDataType: false,
        flex: 1
      },
      rowIndexArr: [
        {
          field: 'rowIndex',
          headerName: '序号',
          width: 100,
          checkboxSelection: true,
          headerCheckboxSelection: true,
          sortable: false,
          pinned: 'left',
          valueGetter: (params) => {
            // 返回当前行的序号
            return params.node.rowIndex + 1
          }
        },
        {
          field: 'handle',
          headerName: '操作',
          width: 140,
          pinned: 'right',
          cellRenderer: 'listBtn'
        }
      ],
      columnDefs: [],
      gridApi: null,
      rowData: null,
      dataSelect: [],
      typeList: jsonData.typeList,
      statusList: jsonData.statusList,
      genderList: jsonData.genderList,
      searchForm: {},
      // 带随访数目
      selectDataList: [],
      tableHeight: 0,
      exercisesDialogBak: false,
      uploadProgress: 0,
      exercisesForm: {
        deptCode: '',
        examName: '',
        examTime: '',
        examTotalScore: '',
        // examScoreMin: '1',
        examText: '',
        examNotes: ''
      },
      exercisesFormRules: {
        deptCode: [{ required: true, message: '试题类型不能为空', trigger: 'change' }],
        examName: [{ required: true, message: '考题名称不能为空', trigger: 'change' }],
        examTime: [{ required: true, message: '考题时长不能为空', trigger: 'change' }],
        examTotalScore: [{ required: true, message: '考题分值不能为空', trigger: 'change' }],
        // examScoreMin: [{ required: true, message: '评分设置不能为空', trigger: 'change' }],
        examText: [{ required: true, message: '考题题干不能为空', trigger: 'change' }],
        examNotes: [{ required: true, message: '注意事项及说明不能为空', trigger: 'change' }]
      },
      deptLoading: false,
      examLoading: false,
      saveLoading: false,
      // 顶部保存loading
      deptOptions: [],
      examOptions: [],
      examScoreMinOptions: [
        {
          label: '0.1',
          value: '0.1'
        },
        {
          label: 0.5,
          value: '0.5'
        },
        {
          label: 1,
          value: '1'
        }
      ],
      activeName: 'scoreCard',
      videoUrl: null,
      // new upload
      url: '',
      exercisesIdBak: '',

      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      // 密码 start
      checkPasswork: '',
      passwordVisible: false,
      passwordForm: {
        password: ''
      },
      passwordFormRules: {
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }]
      },
      passwordCheck: '',
      examinationIdDialog: ''
      // 密码 end
    }
  },
  computed: {
    headerToken () {
      return { Token: Vue.cookie.get('token') }
    }
  },
  created () {
    setTimeout(() => {
      this.url = this.$http.BASE_URL + `/tool/upload/uploadMultipartFile`
      this.tableHeight = this.$refs.tableBox.scrollHeight
      this.getList()
    }, 100)
    this.getHeadersCol()
  },
  methods: {
    onSortChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    onFilterChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    // 获取选中
    getSelectedRows () {
      this.dataSelect = this.gridApi.getSelectedRows()
    },
    // 获取表头
    getHeadersCol () {
      this.columnDefs = []
      setTimeout(() => {
        this.col = JSON.parse(JSON.stringify(listJson.column))
        this.columnDefs = this.rowIndexArr.concat(this.col)
      }, 10)
    },
    // 装载列表
    onGridReady (params) {
      this.gridApi = params.api
    },
    closeHandle () {
      this.exercisesDialogBak = false
      this.getList()
    },
    translateTime (timeStr) {
      let minute = Math.floor((timeStr % 3600) / 60) > 9 ? Math.floor((timeStr % 3600) / 60) : '0' + Math.floor((timeStr % 3600) / 60)
      let second = Math.floor(timeStr % 60) > 9 ? Math.floor(timeStr % 60) : '0' + Math.floor(timeStr % 60)
      return `${minute}:${second}`
    },
    computedGenderList (val) {
      let Arr = this.genderList.filter(item => {
        return item.value === String(val)
      })
      if (Arr.length > 0) {
        return Arr[0].label
      } else {
        return '暂无'
      }
    },
    computeduserLevelId (val) {
      if (val === 0) {
        return '非会员'
      } else {
        return `会员${val}级`
      }
    },
    computedStatus (val) {
      let Arr = this.statusList.filter(item => {
        return item.value === String(val)
      })
      if (Arr.length > 0) {
        return Arr[0].label
      } else {
        return '暂无'
      }
    },
    // 获取数据列表
    getList (page) {
      if (page) {
        this.page.currentPage = page
      }
      this.$http({
        url: '/exam/examination/list',
        method: 'get',
        params: {
          page: this.page.currentPage,
          limit: this.page.pageSize,
          examName: this.searchForm.examName,
          examTypeName: this.searchForm.examTypeName
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.rowData = data.page.records
          this.page.total = data.page.total
        } else {
          this.rowData = []
          this.page.total = 0
        }
      })
    },

    // 每页数
    handleSizeChange (val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getList()
    },
    // 当前页
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getList()
    },

    clearHandle () {
      this.searchForm = {}
      this.page.currentPage = 1
      this.getList()
    },
    handleSelectionChange (val) {
      this.selectDataList = val
    },
    showExercises () {
      // console.log(this.$store.state.user)
      this.exercisesForm = {
        deptCode: '',
        examName: '',
        examTime: '',
        examTotalScore: '',
        // examScoreMin: '1',
        examText: '',
        examNotes: ''
      }
      this.examinationIdDialog = ''
      this.exercisesIdBak = ''
      this.exercisesDialogBak = true
      setTimeout(() => {
        // this.resetForm('exercisesForm')
        this.$refs.tiganDialog.getDept()
        this.$refs.tiganDialog.resetForm()
        // this.$refs.childScoreCard.updateData()
        // this.$refs.childSelfinspectionCard.updateData()
        // this.$refs.childCueCard.updateData()
        // this.$refs.childExampoints.updateData()
      }, 100)
    },
    // 重制密码
    resetItem (val) {
      const h = this.$createElement
      this.$msgbox({
        title: '重置密码',
        message: h('p', null, [
          h('i', { class: 'icon iconfont icon-zhongzhimima', style: 'color: red;font-weight: 600;font-size: 20px !important;padding-right: 10px' }, ''),
          h('span', null, '此操作将重置密码！请确认是否继续')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '操作中...'
            initializePwd({type: 1, id: val.id}).then(res => {
              if (res.data.code === 0) {
                this.$message.success('密码重置成功')
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }
            })
          } else {
            done()
          }
        }
      })
    },
    // 通过密码查看
    passwordEdit (params) {
      this.passwordForm.password = ''
      this.examinationIdDialog = params.id
      this.passwordVisible = true
    },
    handleClosePwd () {
      this.passwordVisible = false
    },
    submitPassword (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          let params = {
            id: this.examinationIdDialog,
            type: 1,
            passwordType: '1',
            password: this.passwordForm.password
          }
          this.passwordCheck = this.passwordForm.password
          authCheck(params).then(res => {
            if (res.data.code === 0) {
              this.$message.success(res.data.msg || '密码正确')
              setTimeout(() => {
                this.$refs['passwordForm'].resetFields()
                this.passwordVisible = false
                this.exercisesDialogBak = true
                setTimeout(() => {
                  this.$refs.tiganDialog.getDept()
                  this.$refs.tiganDialog.getInfo()
                }, 100)
              }, 1000)
            }
          })
        } else {
          return false
        }
      })
    },
    edit (params) {
      this.examinationIdDialog = params.id
      this.exercisesDialogBak = true
      this.passwordForm.password = ''
      setTimeout(() => {
        // this.resetForm('exercisesForm')
        this.$refs.tiganDialog.getDept()
        this.$refs.tiganDialog.getInfo()
      }, 100)
    },
    exercisesFormSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveLoading = true
          // let examName = this.examOptions.filter(val => val.id === this.exercisesForm.examNameCode)[0].examName
          let deptName = this.deptOptions.filter(val => val.id === this.exercisesForm.deptCode)[0].deptName
          if (this.exercisesForm.id) {
            this.$http({
              url: '/exam/examination/update',
              method: 'post',
              data: {
                deptCode: this.exercisesForm.deptCode,
                deptName: deptName,
                examName: this.exercisesForm.examName,
                // examScoreMin: this.exercisesForm.examScoreMin,
                examText: this.exercisesForm.examText,
                createOperatorId: this.$store.state.user.id,
                id: this.exercisesForm.id
              }
            }).then(({ data }) => {
              // console.log(data)
              if (data && data.code === 0) {
                this.saveLoading = false
                this.$message.success('保存成功，请继续上传相关资料')
              } else {
                this.saveLoading = false
              }
            })
          } else {
            let params = {
              deptCode: this.exercisesForm.deptCode,
              deptName: deptName,
              examName: this.exercisesForm.examName,
              examTime: this.exercisesForm.examTime,
              examTotalScore: this.exercisesForm.examTotalScore,
              // examScoreMin: this.exercisesForm.examScoreMin,
              examText: this.exercisesForm.examText,
              examNotes: this.exercisesForm.examNotes,
              createUserId: this.$store.state.user.id,
              createUserName: this.$store.state.user.realName
            }
            console.log(params)
            this.$http({
              url: '/exam/examination/save',
              method: 'post',
              data: params
            }).then(({ data }) => {
              console.log(data)
              if (data && data.code === 0) {
                this.saveLoading = false
                this.$message.success('保存成功，请继续上传相关资料')
                this.exercisesIdBak = data.examinationId
                // 成功之后需要绑定url的路径，
              } else {
                this.saveLoading = false
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 获取科室
    getDept (val) {
      this.deptLoading = true
      this.$http({
        url: '/exam/dept/list',
        method: 'get',
        params: {
          page: 1,
          limit: 10,
          deptName: val
        }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.deptOptions = data.page.records
          // console.log(data)
          this.deptLoading = false
        } else {
          this.deptOptions = []
          this.deptLoading = false
        }
      })
    },
    // 科室变更
    deptChange () {
      // if (this.exercisesForm.dept) {
      //   this.getExam(this.exercisesForm.dept)
      // } else {
      //   this.examOptions = []
      // }
    },

    handleClick (tab, event) {
      console.log(tab, event)
      this.activeName = tab.name
      // if(this.activeName == '')
    },
    delItem (val) {
      const h = this.$createElement
      this.$msgbox({
        title: '删除',
        message: h('p', { style: 'width: 300px;display:flex;' }, [
          h('i', { class: 'el-icon-delete', style: 'color: red;font-size: 24px;font-weight:600;margin-right: 6px' }, ''),
          h('span', null, `请确认是否删除该条题干？`)
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            this.$http({
              url: `/exam/examination/deleteByExaminationId?examinationId=${val.id}`,
              method: 'post'
            }).then(({ data }) => {
              if (data && data.code === 0) {
                instance.confirmButtonLoading = false
                done()
                this.$message.success('删除成功')
                this.getList()
              } else {
                instance.confirmButtonLoading = false
                done()
              }
            })
            setTimeout(() => {
              //
              done()
              setTimeout(() => {
                instance.confirmButtonLoading = false
              }, 300)
            }, 3000)
          } else {
            done()
          }
        }
      })
    }
  }
}
</script>
<style lang="scss">
.exercises-box {
  .el-dialog__body {
    height: calc(100% - 54px) !important;
    padding: 20px 20px;
    overflow: auto;
    // display: flex;
    // flex-direction: column;
  }

  .inner {
    .table-box {
      flex: 1;
      width: 100%;
    }
  }

  .top-box {
    border: 1px solid rgba(10, 115, 78, 0.2);
    border-radius: 6px;
    overflow: hidden;
    margin-bottom: 10px;

    .title {
      width: 100%;
      height: 40px;
      line-height: 40px;
      color: #333;
      font-size: 16px;
      font-weight: 600;
      padding-left: 10px;
      margin: 0;
      margin-bottom: 20px;
      background: rgba(10, 115, 78, 0.2);
      display: flex;
      justify-content: space-between;
    }
  }

  .bottom-box {
    // flex: 1;
    min-height: 400px;
    max-height: 1000px;
    overflow: auto;

    .tab-inner {
      padding: 0 10px;
    }
  }
}

.upload-box {
  height: 60px;

  .el-upload--text {
    position: absolute;
    left: 330px;
  }

  .el-upload-list {
    width: 300px;
    position: absolute;
    left: 0;
    top: 0;
  }

  .el-upload__tip {
    margin-top: 0;
    font-size: 14px;
  }
}
</style>
